package lockx

import (
	"math/rand"
	"sync"
)

// var pool sync.Pool //临时对象池-->缓存可重复利用的对象
// --> 减少内存分配 降低GC
// 创建成本比较高的对象 使用频繁
// Pool长度默认为机器CPU线程数
// 可以无通知被回收
const (
	pool_on  = iota
	pool_off = iota
)

type Conn struct {
	id     int64
	target string
	status int
}

func NewConn(target string) *Conn {

	return &Conn{
		target: target,
		id:     rand.Int63(),
		status: pool_on,
	}
}
func (c Conn) Status() int {
	return c.status

}

type ConnPoolx struct {
	sync.Pool
}

func GetPool(target string) (*ConnPoolx, error) {
	return &ConnPoolx{
		Pool: sync.Pool{
			New: func() any {
				return NewConn(target)
			}}}, nil
}
func (r *ConnPoolx) Get() *Conn {
	conn := r.Pool.Get().(*Conn)
	if conn.status == pool_off {
		conn = r.Pool.New().(*Conn)
	}
	return conn
}
func (r *ConnPoolx) Put(co *Conn) {
	if co.status == pool_off {
		return
	}
	r.Pool.Put(co)
}
